/***************************************************************************
 *   Copyright (C) 2007 by Grzegorz Latarowski   *
 *   g.latarowski@gmail.com   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

// Qt

// lib
#include "gexception.h"

// local
#include "window.h"

const QString xmlVersion( "0.1" );


// TODO: program crushes when trying to create empty p_image



// ===========================================================================
//                                 Window
// ===========================================================================


// --------------------------- Window::Window() ------------------------------
Window::Window() : QMainWindow()
{
		// ui
	setupUi( this );

	statusBar()->showMessage( tr("Load an image.") );

	connect( &_autoClient, SIGNAL( disconnected() ),
			  this, SLOT( clientDisconnected() ) );
	connect( &_updateTimer, SIGNAL( timeout() ), this, SLOT( updateFrame() ) );
	
	// ==============================================
	// setup graphicsROIEditor
	_pRoiEditor = new GRoiEditor();
	graphicsView->setScene( _pRoiEditor );
	graphicsView->setCacheMode(QGraphicsView::CacheBackground);
	graphicsView->setRenderHint( QPainter::Antialiasing );

	_pDocConfig = NULL;
}
// ---------------------------------------------------------------------------


// --------------------------- Window::~Window() -----------------------------
Window::~Window()
{
}
// ---------------------------------------------------------------------------


// ------------------- Window::on_actionNew_triggered() ----------------------
void Window::on_actionNew_triggered()
{
		// clear opened configFileName
	_configFileName.clear();

		// clear regions editor
	if ( _pRoiEditor ) _pRoiEditor->setDefaultRegions();

}
// ---------------------------------------------------------------------------


// -------------------- Window::on_actionOpen_triggered() --------------------
void Window::on_actionOpen_triggered()
{
	QString fileName = QFileDialog::getOpenFileName( this,
			tr( "Open Configuration File" ),
			QDir::currentPath(),
			tr( "Autostop configuration files (*.xml)" ) );
	
	if ( fileName.isEmpty() ) return;
	
	QFile file( fileName );
	if ( !file.open( QFile::ReadOnly | QFile::Text ) )
	{
		QMessageBox::warning( this,
							  tr( "Adjuster" ),
							  tr( "Cannot read file %1:\n%2." )
									  .arg( fileName )
									  .arg( file.errorString() ) );
		return;
	}
	if ( readConfigFile( &file ) )
	{
		statusBar()->showMessage(
				tr( "Configuration file \"%1\" loaded" ).arg( fileName ), 5000 );

			// configuration succesfully read, store opened fileName 
		_configFileName = fileName;
	}
}
// ---------------------------------------------------------------------------


// -------------------- Window::on_actionSaveAs_triggered() ------------------
void Window::on_actionSaveAs_triggered()
{
	QString fileName = QFileDialog::getSaveFileName( this,
			tr( "Save Configuration File" ),
			QDir::currentPath(),
			tr( "Autostop configuration files (*.xml)" ) );
	
	if ( fileName.isEmpty() ) return;

	if( !fileName.endsWith( ".xml" ) ) fileName.append( ".xml" );
	
	QFile file( fileName );
	if ( !file.open( QFile::WriteOnly | QFile::Text ) )
	{
		QMessageBox::warning( this,
							  tr( "Adjuster" ),
							  tr( "Cannot write file %1:\n%2." )
									  .arg( fileName )
									  .arg( file.errorString() ) );
		return;
	}
	
	if ( writeConfigFile( &file ) )
	{
		statusBar()->showMessage(
				tr( "Configuration file \"%1\" saved" ).arg( fileName ), 5000 );

			// configuration succesfully written, store saved fileName
		_configFileName = fileName;
	}
}
// ---------------------------------------------------------------------------


// -------------------- Window::on_actionSave_triggered() --------------------
void Window::on_actionSave_triggered()
{
		// if some config file is opened/saved
	if( !_configFileName.isEmpty() )
	{
		QFile file( _configFileName );
		if ( !file.open( QFile::WriteOnly | QFile::Text ) )
		{
			QMessageBox::warning( this,
								tr( "Adjuster" ),
								tr( "Cannot write file %1:\n%2." )
										.arg( _configFileName )
										.arg( file.errorString() ) );
			return;
		}
		
		if ( writeConfigFile( &file ) )
			statusBar()->showMessage(
					tr( "Configuration file \"%1\" saved" )
					.arg( _configFileName ), 5000 );
	}
	else
	{
			// call save as method
		on_actionSaveAs_triggered();
	}
}
// ---------------------------------------------------------------------------


// ------------------- Window::on_actionLoadImage_triggered() ----------------
void Window::on_actionLoadImage_triggered()
{
	QString dir = ".";
	QString imageFile = QFileDialog::getOpenFileName(
			this,
			tr("Select image file"),
			dir,
			tr("Images (*.bmp *.png *.xpm *.jpg *.jpeg)")
													);
	
	if ( !imageFile.isEmpty() )
	{
		// load content
		
		QPixmap imagePixmap( imageFile );
		if( imagePixmap.isNull() )
		{
			// pixmap is invalid, show warning
			QMessageBox::warning( this,
								  tr("Adjuster Warning"),
								  tr("Cannot open file \"%1\": "
										  "Unrecognized file type." ).arg( imageFile ),
								  QMessageBox::Ok
								);
			return;
		}

			// load pixmap into ROIEditor
		_pRoiEditor->setPixmap( imagePixmap );
			// set deafault regios editors
		_pRoiEditor->setDefaultRegions();
			// show status message
		statusBar()->showMessage( tr("Image \"%1\" loaded").arg( imageFile ), 5000 );

		zoomFitInWidget();
	}
}
// ---------------------------------------------------------------------------


// ------------- Window::on_actionZoomFitToWidth_triggered() -----------------
void Window::on_actionZoomFitToWidth_triggered()
{
	double w     = (double) graphicsView->sceneRect().width();
	double viewW = (double) graphicsView->size().width();
	double scale = viewW / w;
	
	graphicsView->setMatrix( QMatrix().scale( scale, scale ), false );
}
// ---------------------------------------------------------------------------


// ------------- Window::on_actionZoomFitToHeight_triggered() ----------------
void Window::on_actionZoomFitToHeight_triggered()
{
	double h     = graphicsView->sceneRect().height();
	double viewH = graphicsView->size().height();
	double scale = viewH / h;
	
	graphicsView->setMatrix( QMatrix().scale( scale, scale ), false );
}
// ---------------------------------------------------------------------------


// ---------------- Window::on_actionZoomIn_triggered() ----------------------
void Window::on_actionZoomIn_triggered()
{
	graphicsView->scale( 1.2, 1.2 );
}
// ---------------------------------------------------------------------------

    
// -------------  Window::on_actionZoomOut_triggered() -----------------------
void Window::on_actionZoomOut_triggered()
{
	graphicsView->scale( 1 / 1.2, 1 / 1.2 );
}
// ---------------------------------------------------------------------------


// ----------- Window::on_actionZoomOriginalSize_triggered() -----------------
void Window::on_actionZoomOriginalSize_triggered()
{
	graphicsView->setMatrix( QMatrix(), false );
}
// ---------------------------------------------------------------------------


// --------------------- Window::zoomFitInWidget() ---------------------------
void Window::zoomFitInWidget()
{
	double scroolBarOffset = 5;
	
		// get _pixmaps sizes
	double w = (double) graphicsView->sceneRect().width();
	double h = (double) graphicsView->sceneRect().height();
		// get widget sizes
	double viewW = (double) graphicsView->size().width() - scroolBarOffset;
	double viewH = (double) graphicsView->size().height() - scroolBarOffset;
		// calculate scales
	double scaleW = viewW / w;
	double scaleH = viewH / h;
	
		// fit image to width or height (hole image in window)
	if( scaleW > scaleH )
		graphicsView->setMatrix( QMatrix().scale( scaleH, scaleH ), false );
	else
		graphicsView->setMatrix( QMatrix().scale( scaleW, scaleW ), false );
}
// ---------------------------------------------------------------------------




// --------------- Window::on_toolConnect_clicked() --------------------------
void Window::on_toolConnect_clicked()
{
		// connect to camera
	if( toolConnect->isChecked() )
	{
			// if client was connect than disconnect 
		if ( _autoClient.isConnected() ) _autoClient.disconnectFromHost();
			// establish connection 
		try
		{
			// before connection
				// set wait cursor icon
			setCursor( Qt::WaitCursor );
				// set unconnected icon
			toolConnect->setIcon( QIcon( QString::fromUtf8(
					":/res/connect_no.png" ) ) );
					// set new tooltip
			toolConnect->setToolTip( tr( "Disconnected. Click to connect." ) );
				// show status that conencting 
			statusBar()->showMessage( tr( "Connecting to %1..." )
									.arg( lineIP->text() ) );

				// establish connection
			_autoClient.connectToHost( lineIP->text() );
			
			// after connection is established 
				// restore cursor
			setCursor( Qt::ArrowCursor );
			if( _autoClient.isConnected() ) {
					// set status
				statusBar()->showMessage(
						tr( "Connection to %1 established." )
						.arg( lineIP->text() ),	5000 );
					// change connection button icon
				toolConnect->setIcon( QIcon( QString::fromUtf8(
						":/res/connect_established.png") ) );
					// set new tooltip
				toolConnect->setToolTip( tr( "Connected. Click to disconnect." ) );
					// enable buttons which requires valid network connection
				actionPlay->setEnabled( true );
				actionStop->setEnabled( true );
				toolUpdateParams->setEnabled( true );
			}
				// succes 
			return;
		}
		catch( const GException& e )
		{
			statusBar()->showMessage(
					tr("Connection error: %1" ).arg( e.getMessage() ), 5000 );
		}
		
	}
	else
	{
		// if disconnect

			// stop the timer 
		_updateTimer.stop();
		
		if ( _autoClient.isConnected() ) _autoClient.disconnectFromHost();
			// show message
		statusBar()->showMessage( tr( "Disconnected." ), 5000 );
	}

	// defaultly - error or disconnected
	
		// restore cursor
	setCursor( Qt::ArrowCursor );
		// restore button
	toolConnect->setChecked( false );
		// set unconnected icon
	toolConnect->setIcon( QIcon( QString::fromUtf8(
			":/res/connect_no.png" ) ) );
		// set new tooltip
	toolConnect->setToolTip( tr( "Disconnected. Click to connect." ) );
		// disable buttons which requires valid network connection
	actionPlay->setDisabled( true );
	actionStop->setDisabled( true );
	toolUpdateParams->setDisabled( true );
	
}
// ---------------------------------------------------------------------------


// -------------------- Window::clientDisconnected() -------------------------
void Window::clientDisconnected()
{
	// set default as disconnected
	
		// stop the timer 
	_updateTimer.stop();
		// restore cursor
	setCursor( Qt::ArrowCursor );
		// restore button
	toolConnect->setChecked( false );
		// set unconnected icon
	toolConnect->setIcon( QIcon( QString::fromUtf8(
			":/res/connect_no.png" ) ) );
		// set new tooltip
	toolConnect->setToolTip( tr( "Disconnected. Click to connect." ) );
		// show message
	statusBar()->showMessage( tr( "Connection lost." ), 5000 );
		// disable buttons which requires valid network connection
	actionPlay->setDisabled( true );
	actionStop->setDisabled( true );
	toolUpdateParams->setDisabled( true );
}
// ---------------------------------------------------------------------------




// -------------------- Window::on_actionPlay_triggered() --------------------
void Window::on_actionPlay_triggered()
{
		// if connection is established then start timer
	if( _autoClient.isConnected() ) _updateTimer.start( 250 );
		// hide regions tools while playing video stream 
	if( _pRoiEditor ) _pRoiEditor->showTools( false );
}
// ---------------------------------------------------------------------------


// -------------------- Window::on_actionStop_triggered() --------------------
void Window::on_actionStop_triggered()
{
		// stop streaming video 
	_updateTimer.stop();
		// show regions tool while not playing video
	if( _pRoiEditor ) _pRoiEditor->showTools( true );
}
// ---------------------------------------------------------------------------


// --------------------- Window::updateFrame() -------------------------------
void Window::updateFrame()
{
	try
	{
		startClock();
		if( _pRoiEditor ) _pRoiEditor->setPixmap( _autoClient.frame() );
		endClock( "reading frame" );
	}
	catch( const GException& e )
	{
		statusBar()->showMessage(
				tr( "Camera error: %1" ).arg( e.getMessage() ), 5000 );
	}
}
// ---------------------------------------------------------------------------


// ----------------- Window::on_toolUpdateParams_clicked() -------------------
void Window::on_toolUpdateParams_clicked()
{
	try
	{
		if( _pRoiEditor ) _autoClient.sendMarkers( _pRoiEditor->markersImage() );
		if( _pRoiEditor ) _autoClient.sendRoi( _pRoiEditor->roiImage() );
		_autoClient.sendParams( capsulateParams() );
	}
	catch( const GException & e )
	{
		statusBar()->showMessage(
				tr( "Camera error: %1" ).arg( e.getMessage() ), 5000 );
	}
}
// ---------------------------------------------------------------------------


// ---------------------- Window::capsulateParams()---------------------------
QVariantMap Window::capsulateParams()
{
	QVariantMap params;

	for( int i = 0; i < tableParams->rowCount(); i++ )
	{
		if( tableParams->item( i, 0 ) && tableParams->item( i, 1 ) )
		{
			QString name = tableParams->item( i, 0 )
					->data( Qt::DisplayRole ).toString();
			QVariant value = tableParams->item( i, 1 )->data( Qt::DisplayRole );
			params.insert( name, value );
		}
	}
	
	return params;
}
// ---------------------------------------------------------------------------


// -------------------------- Window::startClock() ---------------------------
void Window::startClock()
{
#ifdef Q_OS_UNIX
    gettimeofday( &_clock, NULL );
#else
    _clock = GetTickCount();
#endif
}
// ---------------------------------------------------------------------------


// ------------------------- Window::endClock() ------------------------------
void Window::endClock( const QString description )
{
    double seconds = 0.0;
#ifdef Q_OS_UNIX
    struct timeval end;
    gettimeofday( &end, NULL );

    seconds = (double)end.tv_sec - (double)_clock.tv_sec + 1E-6*end.tv_usec - 1E-6*_clock.tv_usec;
#else        
    seconds = ( GetTickCount() - _clock ) * 0.001;
#endif
	
    statusBar()->showMessage( QString("%1 : %2 [s]").arg( description ).arg( seconds ) );
}
// ---------------------------------------------------------------------------












// --------------------- Window::writeConfigFile() ---------------------------
bool Window::writeConfigFile( QIODevice * pDevice )
{
	if( _pDocConfig ) delete _pDocConfig;
	_pDocConfig = new QDomDocument( "Autostop" );
	if( !_pDocConfig ) return false;

		// create root node for the document 
	QDomElement autostop = _pDocConfig->createElement( "autostop" );
		// create version attribute for root node 
	QDomAttr versionAttr = _pDocConfig->createAttribute( "version" );
	versionAttr.setValue( xmlVersion );
	autostop.setAttributeNode( versionAttr );
		// append autostop (root) note to document 
	_pDocConfig->appendChild( autostop );

		// create camera element and add them to document 
	QDomElement camera = _pDocConfig->createElement( "camera" );
	if( !createCameraElements( camera ) ) return false;
	autostop.appendChild( camera );

		// save file to pDevice 
    const int IndentSize = 4;
    QTextStream out( pDevice );
    _pDocConfig->save( out, IndentSize );
	
	return true;
}
// ---------------------------------------------------------------------------


// ----------------------- Window::createCameraElements() --------------------
bool Window::createCameraElements( QDomElement & camera )
{
		// create identyfication elements 
	QDomElement identyfication = _pDocConfig->createElement( "identyfication" );
	camera.appendChild( identyfication );
	if( !createCameraIdentyfication( identyfication ) ) return false;

		// create settings elements 
	QDomElement settings = _pDocConfig->createElement( "settings" );
	camera.appendChild( settings );
	if( !createCameraSettings( settings ) ) return false;

		// create roi element
	QDomElement roi  = _pDocConfig->createElement( "roi" );
	camera.appendChild( roi );
	if( !createCameraRoi( roi ) ) return false;

		// create marker elements
	QDomElement markers = _pDocConfig->createElement( "markers" );
	camera.appendChild( markers );
	if( !createCameraMarkers( markers ) ) return false;

	return true;
}
// ---------------------------------------------------------------------------


// ------------- Window::createCameraIdentyfication() ------------------------
bool Window::createCameraIdentyfication( QDomElement & identyfication )
{
	if( !_pDocConfig ) return false;
	
	QDomElement name  = _pDocConfig->createElement( "name" );
	identyfication.appendChild( name );
	QDomText nameText = _pDocConfig->createTextNode( lineName->text() );
	name.appendChild( nameText );

	QDomElement serialNumber = _pDocConfig->createElement( "serialNumber" );
	identyfication.appendChild( serialNumber );
	QDomText serialNumberText = _pDocConfig->createTextNode( lineSerialNumber->text() );
	serialNumber.appendChild( serialNumberText );

	QDomElement location = _pDocConfig->createElement( "location" );
	identyfication.appendChild( location );
	QDomText locationText = _pDocConfig->createTextNode( textLocation->toPlainText() );
	location.appendChild( locationText );

		// succes 
	return true;
}
// ---------------------------------------------------------------------------


// ----------------- Window::createCameraSettings() --------------------------
bool Window::createCameraSettings( QDomElement & settings )
{
	Q_UNUSED( settings );

	// TODO Save all settings in xml file
	
	if( !_pDocConfig ) return false;

		// succes
	return true;
}
// ---------------------------------------------------------------------------


// ------------------- Window::createCameraRoi() -----------------------------
bool Window::createCameraRoi( QDomElement & roi )
{
	if( !_pDocConfig || !_pRoiEditor ) return false;

	if( !createPoints( roi, _pRoiEditor->roiNodes() ) ) return false;
	
		// succes 
	return true;
}
// ---------------------------------------------------------------------------


// ------------------ Window::createCameraMarkers() --------------------------
bool Window::createCameraMarkers( QDomElement & markers )
{
	if( !_pDocConfig || !_pRoiEditor ) return false;

	
		// create start marker
	QDomElement startMarker = _pDocConfig->createElement( "startMarker" );
	markers.appendChild( startMarker );
	if( !createPoints( startMarker, _pRoiEditor->startMarkerHooks() ) )
		return false;
	
		// create end marker
	QDomElement endMarker = _pDocConfig->createElement( "endMarker" );
	markers.appendChild( endMarker );
	if( !createPoints( endMarker, _pRoiEditor->endMarkerHooks() ) )
		return false;

		// succes 
	return true;
}
// ---------------------------------------------------------------------------


// -------------------- Window::createPoints() -------------------------------
bool Window::createPoints( QDomElement & parent, const QPolygonF & points )
{
	if( !_pDocConfig ) return false;

	foreach( QPointF point, points )
	{
			// create point
		QDomElement element = _pDocConfig->createElement( "point" );
		parent.appendChild( element );
		
			// create pos x element
		QDomElement x = _pDocConfig->createElement( "x" );
		element.appendChild( x );
		QDomText xText = _pDocConfig->createTextNode( QString::number( point.x() ) );
		x.appendChild( xText );
		
			// create pos y element
		QDomElement y = _pDocConfig->createElement( "y" );
		element.appendChild( y );
		QDomText yText = _pDocConfig->createTextNode( QString::number( point.y() ) );
		y.appendChild( yText );
	}

	return true;
}
// ---------------------------------------------------------------------------


// -------------------- Window::readConfigFile() -----------------------------
bool Window::readConfigFile( QIODevice * pDevice )
{
	if( _pDocConfig ) delete _pDocConfig;
	_pDocConfig = new QDomDocument();
	if( !_pDocConfig ) return false;
	
	QString errorStr;
	int errorLine;
	int errorColumn;
	
	if ( !_pDocConfig->setContent( pDevice, true, &errorStr, &errorLine,
		  &errorColumn ) )
	{
		QMessageBox::information( window(),
								  tr( "Adjuster" ),
								  tr( "Parse error at line %1, "
										  "column %2:\n%3" )
										  .arg( errorLine )
										  .arg( errorColumn )
										  .arg( errorStr )
								);
		return false;
	}
	
	QDomElement autostop = _pDocConfig->documentElement();
	if ( autostop.tagName() != "autostop")
	{
		QMessageBox::information( window(),
								  tr( "Adjuster" ),
								  tr( "The file is not and Autostop "
										  "configuration file." )
								);
		return false;
	}
	else if ( autostop.hasAttribute( "version" )
				 && autostop.attribute( "version" ) != xmlVersion )
	{
		QMessageBox::information( window(),
								  tr( "Adjuster" ),
								  tr( "The file is not and Autostop "
										  "configuration file version %1." )
										  .arg( xmlVersion )
								);
		return false;
	}

		// parese camera elements 
	QDomElement camera = autostop.firstChildElement( "camera" );
	if ( camera.isNull() ) return false;
	if ( !parseCameraElements( camera ) ) return false;

		// succes 
    return true;
}
// ---------------------------------------------------------------------------


// ------------------- Window::parseCameraElements() -------------------------
bool Window::parseCameraElements( QDomElement & camera )
{
		// parse identyfication elements 
	QDomElement identyfication = camera.firstChildElement( "identyfication" );
	if ( identyfication.isNull() ) return false;
	if ( !parseCameraIdentyfication( identyfication ) ) return false;

		// parse settings elements
	QDomElement settings = camera.firstChildElement( "settings" );
	if ( settings.isNull() ) return false;
	if ( !parseCameraSettings( settings ) ) return false;

		// parse roi elements
	QDomElement roi = camera.firstChildElement( "roi" );
	if ( roi.isNull() ) return false;
	if ( !parseCameraRoi( roi ) ) return false;

		// parse marker elements
	QDomElement markers = camera.firstChildElement( "markers" );
	if ( markers.isNull() ) return false;
	if ( !parseCameraMarkers( markers ) ) return false;

	return true;
}
// ---------------------------------------------------------------------------


// ----------------- Window::parseCameraIdentyfication() ---------------------
bool Window::parseCameraIdentyfication( QDomElement & identyfication )
{
		// parse name 
	QDomElement name = identyfication.firstChildElement( "name" );
	if( name.isNull() ) return false;
	lineName->setText( name.text() );

		// parse serialNumber
	QDomElement serialNumber = identyfication.firstChildElement( "serialNumber" );
	if ( serialNumber.isNull() ) return false;
	lineSerialNumber->setText( serialNumber.text() );
	
		// parse location
	QDomElement location = identyfication.firstChildElement( "location" );
	if ( location.isNull() ) return false;
	textLocation->setText( location.text() );

		// succes 
	return true;
}
// ---------------------------------------------------------------------------


// ----------------- Window::parseCameraSettings() ---------------------------
bool Window::parseCameraSettings( QDomElement & settings )
{
	Q_UNUSED( settings );

	// TODO Restore all settings from xml file

	
		// succes
	return true;
}
// ---------------------------------------------------------------------------


// --------------------- Window::parsePoints() -------------------------------
bool Window::parsePoints( QDomElement & parent, QPolygonF * pPoints )
{
		// parse points
	QDomElement point = parent.firstChildElement( "point" );
	while ( !point.isNull() )
	{
			// parse x element from point 
		QDomElement x = point.firstChildElement( "x" );
		if ( x.isNull() ) return false;
		bool ok;
		double xValue = x.text().toDouble( &ok );
			// if conversion to double went wrong return with negative 
		if ( !ok ) return false;

			// parse y element from point 
		QDomElement y = point.firstChildElement( "y" );
		if ( y.isNull() ) return false;
		double yValue = y.text().toDouble( & ok );
			// if conversion to double went wrong return with negative 
		if ( !ok ) return false;

			// add just parsed point to polygon
		pPoints->append( QPointF( xValue, yValue ) );

			// search for next point 
		point = point.nextSiblingElement();
	}

	return true;
}
// ---------------------------------------------------------------------------


// ----------------- Window::parseCameraRoi() --------------------------------
bool Window::parseCameraRoi( QDomElement & roi )
{
	if( !_pRoiEditor ) return false;

		// create empty polygon for nodes
	QPolygonF nodes;

		// parse point 
	if ( !parsePoints( roi, &nodes ) ) return false;

		// set new nodes to roi 
	_pRoiEditor->setRoiNodes( nodes );
	
		// succes 
	return true;
}
// ---------------------------------------------------------------------------


// ------------------ Window::parseCameraMarkers() ---------------------------
bool Window::parseCameraMarkers( QDomElement & markers )
{
	if( !_pRoiEditor ) return false;

		// parse start marker
	QDomElement startMarker = markers.firstChildElement( "startMarker" );
	if( startMarker.isNull() ) return false;
		// create empty polygon for start markers hooks
	QPolygonF startHooks;
		// parse start markers hooks
	if( !parsePoints( startMarker, &startHooks ) ) return false;
		// set new hooks to start markers
	_pRoiEditor->setStartMarkerHooks( startHooks[0], startHooks[1] );

		// parse end marker
	QDomElement endMarker = markers.firstChildElement( "endMarker" );
	if( endMarker.isNull() ) return false;
		// create empty polygon for end markers hooks
	QPolygonF endHooks;
		// parse end markers hooks
	if( !parsePoints( endMarker, &endHooks ) ) return false;
		// set new hooks to end markers
	_pRoiEditor->setEndMarkerHooks( endHooks[0], endHooks[1] );

		// succes 
	return true;
}
// ---------------------------------------------------------------------------



// eof
